<?php
//Requires connectDB and createNewQREntry
require("dbFunctions.php");

/**
 * Adds a new Room resource to the database
 * This file should be hidden from users using the web interface and is used to populate the database
 * from the mobile device specifically.
 *
 * Author: Armand Pallino
 * Date: 10/27/2012
 */

//Get the parameters
$building = $_REQUEST['building'];
$floor = $_REQUEST['floor'];
$room_number = $_REQUEST['room_num'];
$room_type = $_REQUEST['room_type'];


//Verify that equipment name, serial number, and 
//current condition are non-null.
if( is_null($building) )
	die("Building is not provided.");
if( is_null($floor) )
	die("Floor number is not provided.");
if( is_null($room_number) )
	die("Room number is not provided.");
if( is_null($room_type) )
	die("Room type is not provided.");

//Get a PDO Database connection
$dbh = connectDB();

//Try to find the QR Code for the fields provided
$qr_code = roomIDByFields($building,$floor,$room_number);

//-1 means it doesn't exist
if( $qr_code == -1 )
{
	//Create a new QR Code for this Room
	$qr_code = createNewQREntry("Room");

	//Construct the query to add a new Room
	$query =  "INSERT INTO Room (qr_code, building, floor, room_number, room_type) VALUES (:qr_code, :building, :floor, :room_num, :room_type)";

	//Create a PDO Statement by preparing the query
	$stmt = $dbh->prepare( $query );

	//Bind parameters to avoid SQL injection
	$stmt->bindParam(':qr_code', $qr_code);
	$stmt->bindParam(':building', $building);
	$stmt->bindParam(':floor', $floor);
	$stmt->bindParam(':room_num', $room_number);
	$stmt->bindParam(':room_type', $room_type);

	//Execute the PDO Statement
	$stmt->execute();
}
//It did exist...
else
{
	$query = "UPDATE QR_Code SET is_active=1 WHERE qr_code=:qr_code";
	$stmt = $dbh->prepare($query);
	$stmt->bindParam(':qr_code',$qr_code);
	$stmt->execute();
}
//Release the PDO Statement and PDO database connection
$stmt = null;
$dbh = null;

print($qr_code);
?>
